// wordDataManager.js - 词书和单词数据管理工具
// 提供单例模式的单词数据管理器
let instance = null;

// 导入存储管理器
const storageManager = require('./storageManager').getInstance();

/**
 * 单词宝库数据管理类
 * 负责词书、单词和分类的存储、查询、更新和删除操作
 */
class WordDataManager {
  constructor() {
    // 初始化学习数据管理器为null，稍后在initialize方法中初始化
    this.wordLearningDataManager = null;
  }

  /**
   * 生成10位字符的UUID
   * @private
   * @returns {string} 10位UUID字符串
   */
  _generateUUID() {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 10; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }

  // ============= 词书管理 =============

  /**
   * 获取所有词书
   * @returns {Array} 词书数组
   */
  getAllBooks() {
    const books = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_BOOKS) || this._getDefaultBooks();
    return books;
  }

  /**
   * 获取当前激活的词书ID
   * @returns {string|null} 激活词书的ID或null
   */
  getActiveBookId() {
    const books = this.getAllBooks();
    const activeBook = books.find(book => book.active === 1);
    return activeBook ? activeBook.id : null;
  }

  /**
   * 获取指定词书
   * @param {string} bookId - 词书ID
   * @returns {Object|null} 词书对象或null
   */
  getBookById(bookId) {
    const books = this.getAllBooks();
    return books.find(book => book.id === bookId) || null;
  }

  /**
   * 添加新词书
   * @param {Object} bookData - 词书数据
   * @returns {string} 新增词书的ID
   */
  addBook(bookData) {
    const books = this.getAllBooks();
    const newBook = {
      ...bookData,
      id: bookData.id || `book_${this._generateUUID()}`,
      // 确保wordIds数组没有重复项
      wordIds: bookData.wordIds && Array.isArray(bookData.wordIds) ? [...new Set(bookData.wordIds)] : [],
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };
    
    books.push(newBook);
    this._saveBooks(books);
    return newBook.id;
  }

  /**
   * 更新词书
   * @param {string} bookId - 词书ID
   * @param {Object} updateData - 更新数据
   * @returns {boolean} 是否更新成功
   */
  updateBook(bookId, updateData) {
    const books = this.getAllBooks();
    const bookIndex = books.findIndex(book => book.id === bookId);
    
    if (bookIndex === -1) {
      return false;
    }

    if (updateData.active === 1) {
      // 激活词书时，先将所有其他词书设为非激活
      books.forEach(book => {
        if (book.id !== bookId) {
          book.active = 0;
        }
      });
    }
    
    // 创建更新后的数据对象
    const updatedData = {
      ...books[bookIndex],
      ...updateData,
      updateTime: new Date().toISOString()
    };
    
    // 如果更新数据中包含wordIds，则对其进行去重
    if (updateData.wordIds && Array.isArray(updateData.wordIds)) {
      updatedData.wordIds = [...new Set(updateData.wordIds)];
    }
    
    books[bookIndex] = updatedData;
    
    this._saveBooks(books);
    return true;
  }

  /**
   * 删除词书
   * @param {string} bookId - 词书ID
   * @returns {boolean} 是否删除成功
   */
  deleteBook(bookId) {
    let books = this.getAllBooks();
    const initialLength = books.length;
    
    books = books.filter(book => book.id !== bookId);
    
    if (books.length === initialLength) {
      return false;
    }
    
    this._saveBooks(books);
    return true;
  }

  // ============= 单词管理 =============

  /**
   * 获取所有单词
   * @returns {Object} 单词字典 {wordId: wordData}
   */
  getAllWords() {
    const words = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_DICTIONARY) || this._getDefaultWords();
    return words;
  }

  /**
   * 获取指定单词
   * @param {string} wordId - 单词ID
   * @param {string} bookId - 词书ID（可选），用于获取该词书下的特定设置
   * @returns {Object|null} 单词对象或null
   */
  getWordById(wordId) {
    const words = this.getAllWords();
    return words[wordId] || null;
  }

  /**
   * 获取词书中的所有单词（包含词书特定翻译）
   * @param {string} bookId - 词书ID
   * @returns {Array} 单词数组
   */
  getWordsByBookIdWithTranslations(bookId) {
    const book = this.getBookById(bookId);
    if (!book || !book.wordIds || book.wordIds.length === 0) {
      return [];
    }
    
    const wordsDict = this.getAllWords();
    const words = book.wordIds.map(wordId => {
      return wordsDict[wordId] || null;
    }).filter(Boolean);
    
    return words;
  }

  /**
   * 获取词书中的所有单词
   * @param {string} bookId - 词书ID
   * @returns {Array} 单词数组（去除重复项）
   */
  getWordsByBookId(bookId) {
    const book = this.getBookById(bookId);
    if (!book || !book.wordIds || book.wordIds.length === 0) {
      return [];
    }
    
    // 去除wordIds数组中的重复项
    const uniqueWordIds = [...new Set(book.wordIds)];
    
    const wordsDict = this.getAllWords();
    const words = uniqueWordIds.map(wordId => {
      const word = wordsDict[wordId];
      if (!word) return null;
      
      // 不再设置顶级isLearned字段，学习状态将通过learnCount>0判断
      return word;
    }).filter(Boolean);
    return words;
  }
  
  /**
   * 获取学习用的单词（包含词书特定翻译）
   * 这个方法专门用于学习场景，确保用户看到的是当前词书特有的翻译
   * @param {string} wordId - 单词ID
   * @param {string} bookId - 词书ID
   * @returns {Object|null} 单词对象或null
   */
  getWordForLearning(wordId, bookId) {
    // 调用已有的getWordById方法，传入词书ID以获取特定翻译
    return this.getWordById(wordId, bookId);
  }

  /**
   * 添加新单词
   * @param {Object} wordData - 单词数据
   * @returns {string} 新单词的ID
   */
  addWord(wordData) {
    const words = this.getAllWords();
    const wordIndex = Object.keys(words).length + 1; // 获取单词数量+1作为序号索引
    // const newWordId = `word_${wordIndex}_${this._generateUUID()}`;
    const newWordId = `word_${wordIndex}`;

    words[newWordId] = {
      id: newWordId,
      english: wordData.english || '',
      chinese: wordData.chinese || '',
      categories: wordData.categories || undefined,
      groups: wordData.groups || undefined,
      images: wordData.images || undefined,
      pronunciation: wordData.pronunciation || undefined, // 添加发音字段
      // phrases: wordData.phrases || undefined, // 添加词组字段
      examples: wordData.examples || undefined, // 添加例句字段
      // synonyms: wordData.synonyms || [], // 添加近义词字段
      // antonyms: wordData.antonyms || [], // 添加反义词字段
      // 移除bookRelationInfo，使用learningInfo管理学习状态
    };
    
    this._saveWords(words);
    return newWordId;
  }

  /**
   * 更新单词
   * @param {string} wordId - 单词ID
   * @param {Object} updateData - 更新数据
   * @returns {boolean} 是否更新成功
   */
  updateWord(wordId, updateData) {
    const words = this.getAllWords();
    
    if (!words[wordId]) {
      return false;
    }
    
    // 合并更新数据
    const updatedWord = {
      ...words[wordId],
      ...updateData
    };
    
    words[wordId] = updatedWord;
    this._saveWords(words);
    return true;
  }

  /**
   * 批量更新单词分类
   * @param {Array} wordIds - 单词ID数组
   * @param {Array} categories - 分类数组
   * @returns {boolean} 是否更新成功
   */
  updateWordsCategories(wordIds, categories) {
    const words = this.getAllWords();
    let updated = false;
    
    wordIds.forEach(wordId => {
      if (words[wordId]) {
        words[wordId].categories = categories;
        updated = true;
      }
    });
    
    if (updated) {
      this._saveWords(words);
    }
    
    return updated;
  }

  /**
   * 设置单词的记忆状态
   * @param {string} wordId - 单词ID
   * @param {boolean} isMemorized - 是否记住
   * @returns {boolean} 是否设置成功
   */
  setWordMemorizedStatus(wordId, isMemorized) {
    // 使用已初始化的wordLearningDataManager设置记忆状态
    if (!this.wordLearningDataManager) {
      console.error('WordLearningDataManager 未初始化');
      return false;
    }
    return this.wordLearningDataManager.setWordMemorizedStatus(wordId, isMemorized);
  }
  
  /**
   * 获取单词的记忆状态
   * @param {string} wordId - 单词ID
   * @returns {boolean} 记忆状态，默认返回false（未记住）
   */
  getWordMemorizedStatus(wordId) {
    // 使用已初始化的wordLearningDataManager获取记忆状态
    if (!this.wordLearningDataManager) {
      console.error('WordLearningDataManager 未初始化');
      return false;
    }
    return this.wordLearningDataManager.getWordMemorizedStatus(wordId);
  }
  
  /**
   * 批量设置单词的记忆状态
   * @param {Array} wordIds - 单词ID数组
   * @param {boolean} isMemorized - 是否记住
   * @returns {boolean} 是否设置成功
   */
  batchSetWordsMemorizedStatus(wordIds, isMemorized) {
    // 使用已初始化的wordLearningDataManager批量设置记忆状态
    if (!this.wordLearningDataManager) {
      console.error('WordLearningDataManager 未初始化');
      return false;
    }
    return this.wordLearningDataManager.batchSetWordsMemorizedStatus(wordIds, isMemorized);
  }
  
  /**
   * 设置单词的学习状态
   * @deprecated 此方法已不再使用，学习状态通过learnCount>0判断
   * @param {string} wordId - 单词ID
   * @param {string} bookId - 词书ID (仅为了保持兼容性)
   * @param {boolean} isLearned - 是否学过
   * @returns {boolean} 是否设置成功
   */
  setWordLearnedStatus(wordId, bookId, isLearned) {
    console.warn('setWordLearnedStatus方法已不再使用，学习状态通过learnCount>0判断');
    // 使用incrementWordLearnCount方法代替
    if (isLearned) {
      // 为了保持兼容性，如果设置为已学习，则增加学习次数
      return this.incrementWordLearnCount(wordId) > 0;
    }
    
    // 使用已初始化的wordLearningDataManager重置学习数据
    if (!this.wordLearningDataManager) {
      console.error('WordLearningDataManager 未初始化');
      return false;
    }
    return this.wordLearningDataManager.updateLearningData(wordId, {
      learnCount: 0,
      lastLearnTime: null
    });
  }
  
  /**
   * 获取单词的学习状态
   * @param {string} wordId - 单词ID
   * @returns {boolean} 学习状态，通过learnCount>0判断，默认返回false（未学过）
   */
  getWordLearnedStatus(wordId) {
    // 直接使用getWordLearnCount方法判断
    const learnCount = this.getWordLearnCount(wordId);
    return learnCount > 0;
  }
  
  /**
   * 增加单词的学习次数
   * @param {string} wordId - 单词ID
   * @returns {number} 更新后的学习次数
   */
  incrementWordLearnCount(wordId) {
    // 使用已初始化的wordLearningDataManager增加学习次数
    if (!this.wordLearningDataManager) {
      console.error('WordLearningDataManager 未初始化');
      return 0;
    }
    return this.wordLearningDataManager.incrementWordLearnCount(wordId);
  }
  
  /**
   * 获取单词的学习次数
   * @param {string} wordId - 单词ID
   * @returns {number} 学习次数，默认返回0
   */
  getWordLearnCount(wordId) {
    // 使用已初始化的wordLearningDataManager获取学习次数
    if (!this.wordLearningDataManager) {
      console.error('WordLearningDataManager 未初始化');
      return 0;
    }
    return this.wordLearningDataManager.getWordLearnCount(wordId);
  }
  
  /**
   * 获取单词的最后学习时间
   * @param {string} wordId - 单词ID
   * @returns {string|null} 最后学习时间，默认返回null
   */
  getWordLastLearnTime(wordId) {
    // 使用已初始化的wordLearningDataManager获取最后学习时间
    if (!this.wordLearningDataManager) {
      console.error('WordLearningDataManager 未初始化');
      return null;
    }
    return this.wordLearningDataManager.getWordLastLearnTime(wordId);
  }
  
  /**
   * 批量设置单词在特定词书下的学习状态
   * @deprecated 此方法已不再使用，学习状态通过learnCount>0判断
   * @param {Array} wordIds - 单词ID数组
   * @param {string} bookId - 词书ID
   * @param {boolean} isLearned - 是否学过
   * @returns {boolean} 是否设置成功
   */
  batchSetWordsLearnedStatus(wordIds, bookId, isLearned) {
    console.warn('batchSetWordsLearnedStatus方法已不再使用，学习状态通过learnCount>0判断');
    
    // 为了保持兼容性，如果设置为已学习，则增加学习次数
    if (isLearned) {
      let allSuccess = true;
      wordIds.forEach(wordId => {
        const result = this.incrementWordLearnCount(wordId, bookId);
        if (result <= 0) {
          allSuccess = false;
        }
      });
      return allSuccess;
    }
    
    // 如果设置为未学习，由于我们不再使用isLearned字段，所以这里不做任何操作
    // 如果需要重置学习状态，应该考虑专门的resetWordLearnCount方法
    return false;
  }
  
  // ============= 分类管理 =============

  /**
   * 获取所有分类
   * @returns {Array} 分类数组（按自然排序）
   */
  getAllCategories() {
    const categories = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_CATEGORIES) || this._getDefaultCategories();
    
    // 应用自然排序，正确处理包含数字的分类名称
    return categories.sort((a, b) => {
      const aNum = parseInt(a.match(/\d+/)?.[0]);
      const bNum = parseInt(b.match(/\d+/)?.[0]);
      
      // 如果两个字符串都包含数字，则按数字排序
      if (!isNaN(aNum) && !isNaN(bNum)) {
        return aNum - bNum;
      }
      // 如果只有一个包含数字，则包含数字的排前面
      if (!isNaN(aNum)) return -1;
      if (!isNaN(bNum)) return 1;
      // 如果都不包含数字，则按字符串默认排序
      return a.localeCompare(b);
    });
  }

  /**
   * 添加新分类
   * @param {string} categoryName - 分类名称
   * @returns {boolean} 是否添加成功
   */
  addCategory(categoryName) {
    if (!categoryName || categoryName.trim() === '') {
      return false;
    }
    
    const categories = this.getAllCategories();
    
    if (categories.includes(categoryName.trim())) {
      return false;
    }
    
    categories.push(categoryName.trim());
    this._saveCategories(categories);
    return true;
  }

  /**
   * 删除分类
   * @param {string} categoryName - 分类名称
   * @returns {boolean} 是否删除成功
   */
  deleteCategory(categoryName) {
    let categories = this.getAllCategories();
    const initialLength = categories.length;
    
    categories = categories.filter(cat => cat !== categoryName);
    
    if (categories.length === initialLength) {
      return false;
    }
    
    // 从所有单词中移除该分类
    const words = this.getAllWords();
    Object.keys(words).forEach(wordId => {
      words[wordId].categories = words[wordId].categories.filter(cat => cat !== categoryName);
    });
    
    this._saveCategories(categories);
    this._saveWords(words);
    return true;
  }

  /**
   * 获取指定分类下的单词
   * @param {string} categoryName - 分类名称
   * @returns {Array} 单词数组
   */
  getWordsByCategory(categoryName) {
    const wordsDict = this.getAllWords();
    const words = Object.values(wordsDict)
      .filter(word => word.categories && word.categories.includes(categoryName))
      .map(word => {
        // 不再设置isLearned字段，学习状态将通过learnCount>0判断
        return word;
      });
    return words;
  }

  // ============= 发音设置管理 =============

  /**
   * 获取发音设置
   * @returns {Object} 发音设置对象
   */
  getPronunciationSettings() {
    const settings = storageManager.getStorage(storageManager.STORAGE_KEYS.PRONUNCIATION_SETTINGS) || this._getDefaultPronunciationSettings();
    return settings;
  }

  /**
   * 更新发音设置
   * @param {Object} newSettings - 新的发音设置
   * @returns {boolean} 是否更新成功
   */
  updatePronunciationSettings(newSettings) {
    try {
      const currentSettings = this.getPronunciationSettings();
      const updatedSettings = {
        ...currentSettings,
        ...newSettings,
        updateTime: new Date().toISOString()
      };

      storageManager.setStorage(storageManager.STORAGE_KEYS.PRONUNCIATION_SETTINGS, updatedSettings);
      return true;
    } catch (error) {
      console.error('更新发音设置失败:', error);
      return false;
    }
  }

  /**
   * 获取发音方式
   * @returns {string} 发音方式 ('american' 或 'british')
   */
  getPronunciationType() {
    const settings = this.getPronunciationSettings();
    return settings.pronunciationType || 'american';
  }

  /**
   * 设置发音方式
   * @param {string} type - 发音方式 ('american' 或 'british')
   * @returns {boolean} 是否设置成功
   */
  setPronunciationType(type) {
    if (type !== 'american' && type !== 'british') {
      console.warn('无效的发音方式:', type);
      return false;
    }
    return this.updatePronunciationSettings({ pronunciationType: type });
  }

  /**
   * 获取播放倍速
   * @returns {number} 播放倍速 (0.5-2.0)
   */
  getPlaybackSpeed() {
    const settings = this.getPronunciationSettings();
    return settings.playbackSpeed || 1.0;
  }

  /**
   * 设置播放倍速
   * @param {number} speed - 播放倍速 (0.5-2.0)
   * @returns {boolean} 是否设置成功
   */
  setPlaybackSpeed(speed) {
    if (speed < 0.5 || speed > 2.0) {
      console.warn('无效的播放倍速:', speed, '倍速范围应为0.5-2.0');
      return false;
    }
    return this.updatePronunciationSettings({ playbackSpeed: speed });
  }

  /**
   * 获取自动播放设置
   * @returns {boolean} 是否自动播放发音
   */
  getAutoPlay() {
    const settings = this.getPronunciationSettings();
    return settings.autoPlay !== undefined ? settings.autoPlay : true;
  }

  /**
   * 设置自动播放发音
   * @param {boolean} autoPlay - 是否自动播放发音
   * @returns {boolean} 是否设置成功
   */
  setAutoPlay(autoPlay) {
    return this.updatePronunciationSettings({ autoPlay });
  }

  /**
   * 获取默认发音设置
   * @private
   * @returns {Object} 默认发音设置
   */
  _getDefaultPronunciationSettings() {
    return {
      pronunciationType: 'american', // 默认美式发音
      playbackSpeed: 1.0, // 默认正常速度
      autoPlay: true, // 默认自动播放发音
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };
  }

  // ============= 导入导出 =============

  /**
   * 从TXT文件导入词书
   * @param {string} filePath - 文件路径
   * @param {string} bookName - 词书名称
   * @returns {Promise<Object>} 导入结果
   */
  importBookFromTxt(filePath, bookName) {
    return new Promise((resolve, reject) => {
      // 读取文件内容
      wx.getFileSystemManager().readFile({
        filePath: filePath,
        encoding: 'utf-8',
        success: (res) => {
          try {
            const content = res.data;
            const lines = content.split('\n');
            const wordIds = [];
            let skippedLines = [];
            
            // 解析每一行单词
            lines.forEach((line, index) => {
              const lineNumber = index + 1;
              if (line.trim()) {
                const parts = line.trim().split(/\t+/);
                if (parts.length >= 2) {
                  const english = parts[0];
                  const chinese = parts[1];
                  const groups = parts.length > 2 ? parts[2].split(';') : [];
                  const categories = parts.length > 3 ? parts[3].split(';') : [];
                  
                  // 检查单词是否已存在
                  // 修改：现在不仅检查英文单词，还要考虑中文意思，以便区分同形但不同含义的单词
                  const words = this.getAllWords();
                  let wordId = Object.keys(words).find(id => 
                    words[id].english.toLowerCase() === english.toLowerCase() && 
                    words[id].chinese === chinese
                  );
                  
                  // 如果不存在则创建新单词
                  if (!wordId) {
                    // 检查是否存在相同英文但不同中文的单词
                    const hasSameEnglishDifferentChinese = Object.keys(words).some(id => 
                      words[id].english.toLowerCase() === english.toLowerCase() && 
                      words[id].chinese !== chinese
                    );
                    
                    wordId = this.addWord({
                      english,
                      chinese,
                      categories,
                      groups,
                      bookTranslations: {}
                    });
                    
                    if (hasSameEnglishDifferentChinese) {
                      console.log(`第${lineNumber}行: 新增单词 "${english}"（中文：${chinese}），已存在同名但不同含义的单词`);
                    }
                  } else {
                    console.log(`第${lineNumber}行: 单词 "${english}"（中文：${chinese}）已存在，更新信息`);
                    // 如果存在则更新分类、分组和词书特定设置
                    const currentCategories = words[wordId].categories || [];
                    const currentGroups = words[wordId].groups || [];
                    const newCategories = [...new Set([...currentCategories, ...categories])];
                    const newGroups = [...new Set([...currentGroups, ...groups])];
                    
                    // 先查找是否存在同名词书
                    const existingBooks = this.getAllBooks();
                    const existingBook = existingBooks.find(b => b.name === bookName);
                    
                    // 注意：learningInfo现在由wordLearningDataManager单独管理，不再存储在单词数据中
                    
                    // 将当前导入的中文翻译保存到bookRelation
                    bookRelation.translation = chinese;
                    
                    this.updateWord(wordId, { 
                      categories: newCategories, 
                      groups: newGroups
                    });
                  }
                  
                  wordIds.push(wordId);
                } else {
                  console.warn(`第${lineNumber}行: 格式不正确，部分少于2个，跳过该行: "${line}"`);
                  skippedLines.push({ lineNumber, content: line });
                }
              } else {
                console.log(`第${lineNumber}行: 空行，跳过`);
              }
            });
            
            // 创建或更新词书
            let bookId;
            const existingBooks = this.getAllBooks();
            const existingBook = existingBooks.find(book => book.name === bookName);
            
            if (existingBook) {
              // 更新现有词书，确保wordIds没有重复
              const uniqueWordIds = [...new Set(wordIds)];
              this.updateBook(existingBook.id, { wordIds: uniqueWordIds, updateTime: new Date().toISOString() });
              bookId = existingBook.id;
            } else {
              // 创建新词书，确保wordIds没有重复
              const uniqueWordIds = [...new Set(wordIds)];
              bookId = this.addBook({
                name: bookName,
                type: 'custom',
                wordIds: uniqueWordIds
              });
            }
            
            // 记录导入结果
            console.log(`文件解析完成: 共${lines.length}行，成功导入${wordIds.length}个单词，跳过${skippedLines.length}行`);
            if (skippedLines.length > 0) {
              console.warn(`跳过的行: ${JSON.stringify(skippedLines)}`);
            }
            
            resolve({ 
              success: true, 
              bookId, 
              wordCount: wordIds.length, 
              totalLines: lines.length, 
              skippedLines: skippedLines.length,
              skippedDetails: skippedLines
            });
          } catch (error) {
            reject({ success: false, message: '解析文件失败: ' + error.message });
          }
        },
        fail: (error) => {
          reject({ success: false, message: '读取文件失败: ' + error.errMsg });
        }
      });
    });
  }

  /**
   * 导出词库为TXT文件
   * @param {string} bookId - 词书ID，可选，不指定则导出全部
   * @returns {Promise<Object>} 导出结果
   */
  exportDictionaryToTxt(bookId = null) {
    return new Promise((resolve, reject) => {
      try {
        let words = [];
        
        if (bookId) {
          // 导出指定词书
          words = this.getWordsByBookId(bookId);
        } else {
          // 导出全部单词
          words = Object.values(this.getAllWords());
        }
        
        // 生成TXT内容
        let txtContent = '';
        words.forEach(word => {
          const groupsStr = word.groups && word.groups.length > 0 ? 
            ' ' + word.groups.join(';') : '';
          const categoriesStr = word.categories && word.categories.length > 0 ? 
            ' ' + word.categories.join(';') : '';
          txtContent += `${word.english} ${word.chinese}${groupsStr}${categoriesStr}\n`;
        });
        
        // 保存文件到本地
        const fileName = bookId ? 
          `${this.getBookById(bookId).name || '词书'}_导出.txt` : 
          `单词库导出_${new Date().getTime()}.txt`;
        
        const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
        wx.getFileSystemManager().writeFile({
          filePath: filePath,
          data: txtContent,
          encoding: 'utf-8',
          success: () => {
            resolve({ success: true, filePath, fileName });
          },
          fail: (error) => {
            reject({ success: false, message: '保存文件失败: ' + error.errMsg });
          }
        });
      } catch (error) {
        reject({ success: false, message: '导出失败: ' + error.message });
      }
    });
  }

  // ============= 私有方法 =============

  /**
   * 保存词书数据到本地存储
   * @private
   * @param {Array} books - 词书数组
   */
  _saveBooks(books) {
    storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_BOOKS, books);
  }

  /**
   * 保存单词数据到本地存储
   * @private
   * @param {Object} words - 单词字典
   */
  _saveWords(words) {
    storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_DICTIONARY, words);
  }

  /**
   * 保存分类数据到本地存储
   * @private
   * @param {Array} categories - 分类数组
   */
  _saveCategories(categories) {
    storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_CATEGORIES, categories);
  }

  /**
   * 获取默认词书数据
   * @private
   * @returns {Array} 默认词书数组
   */
  _getDefaultBooks() {
    const books = [
    ];
    
    return books;
  }

  /**
   * 获取默认单词数据
   * @private
   * @returns {Object} 默认单词字典
   */
  _getDefaultWords() {
    const words = {
    };
    
    // 将单词添加到默认词书中
    const books = this.getAllBooks();
    if (books.length > 0) {
      books[0].wordIds = ['word_1', 'word_2'];
      books[0].updateTime = new Date().toISOString();
      
      if (books.length > 1) {
        books[1].wordIds = ['word_5'];
        books[1].updateTime = new Date().toISOString();
      }
      
      this._saveBooks(books);
    }
    
    return words;
  }

  /**
   * 获取默认分类数据
   * @private
   * @returns {Array} 默认分类数组
   */
  _getDefaultCategories() {
    return ['食物', '水果', '动物', '宠物', '日常用语', '问候', '学习', '学校', '家庭', '交通'];
  }

  /**
   * 判断单词是否已经丰富（包含发音、例句、词组等详细信息）
   * @private
   * @param {Object} word - 单词对象
   * @returns {boolean} 是否已经丰富
   */
  _isWordEnriched(word) {
    // 定义丰富的标准：包含发音信息、例句和词组
    // 可以根据实际需求调整这个标准
    return word && 
           word.pronunciation 
          //  word.pronunciation.uk && 
          //  word.pronunciation.us && 
          //  word.pronunciation.audio && 
          //  word.pronunciation.audio.uk && 
          //  word.pronunciation.audio.us &&
          //  word.examples && 
          //  word.examples.length > 0 &&
          //  word.phrases && 
          //  word.phrases.length > 0;
  }

  /**
   * 丰富单词数据（获取发音、例句、词组等）
   * @param {Array} wordIds - 单词ID数组
   * @param {Object} options - 配置选项
   * @returns {Promise} 丰富后的单词数组
   */
  enrichWords(wordIds, options = {}) {
    return new Promise((resolve, reject) => {
      try {
        const wordsDict = this.getAllWords();
        const words = wordIds.map(wordId => wordsDict[wordId]).filter(Boolean);
        
        // 如果没有单词，直接返回
        if (words.length === 0) {
          if (options.onComplete) {
            options.onComplete(words);
          }
          resolve([]);
          return;
        }
        
        // 过滤出尚未丰富的单词
        const unenrichedWords = words.filter(word => !this._isWordEnriched(word));
        const alreadyEnrichedWords = words.filter(word => this._isWordEnriched(word));
        
        console.log(`共${words.length}个单词，其中${alreadyEnrichedWords.length}个已丰富，${unenrichedWords.length}个需要丰富`);
        
        // 如果所有单词都已经丰富，直接返回结果
        if (unenrichedWords.length === 0) {
          console.log('所有单词已丰富，无需请求新数据');
          if (options.onComplete) {
            options.onComplete(words);
          }
          resolve(words);
          return;
        }

        // 使用不依赖worker的WordFetcherDirect
        const { WordFetcherDirect } = require('../utils/wordFetcherDirect');
        const wordFetcher = new WordFetcherDirect();
        
        // 只获取未丰富的单词详情
        wordFetcher.fetchWordDetails(unenrichedWords, {
          onProgress: (progress) => {
            console.log('丰富单词进度:', progress);
            if (options.onProgress) {
              options.onProgress(progress);
            }
          },
          onComplete: (enrichedResults) => {
            console.log(`丰富单词完成，成功丰富${enrichedResults.length}个单词`);
            
            // 保存丰富后的单词数据
            const updatedWordsDict = this.getAllWords();
            
            enrichedResults.forEach(word => {
              if (updatedWordsDict[word.id]) {
                // 保留原有的词书相关设置
                updatedWordsDict[word.id] = word;
              }
            });
            
            this._saveWords(updatedWordsDict);
            
            // 合并已丰富的单词和新丰富的单词
            const allResults = [...alreadyEnrichedWords, ...enrichedResults];
            
            if (options.onComplete) {
              options.onComplete(allResults);
            }
            
            resolve(allResults);
          },
          onError: (error) => {
            console.error('丰富单词数据失败:', error);
            
            // 即使出错，也返回已丰富的单词
            const partialResults = alreadyEnrichedWords;
            
            if (options.onError) {
              options.onError(error);
            }
            
            // 调用onComplete回调提供部分结果
            if (options.onComplete && partialResults.length > 0) {
              options.onComplete(partialResults);
            }
            
            reject(error);
          }
        });
      } catch (error) {
        console.error('丰富单词数据异常:', error);
        reject(error);
      }
    });
  }

  /**
   * 同步词书单词数据
   * @param {string} bookId - 词书ID
   * @param {Object} options - 配置选项
   * @returns {Promise} 同步结果
   */
  syncBookWords(bookId, options = {}) {
    return new Promise((resolve, reject) => {
      try {
        const book = this.getBookById(bookId);
        if (!book) {
          throw new Error('词书不存在');
        }
        
        if (!book.wordIds || book.wordIds.length === 0) {
          resolve({ success: true, message: '词书没有单词需要同步' });
          return;
        }
        
        // 丰富单词数据
        this.enrichWords(book.wordIds, {
          onProgress: (progress) => {
            if (options.onProgress) {
              options.onProgress(progress);
            }
          },
          onComplete: (results) => {
            // 更新词书的同步状态
            this.updateBook(bookId, {
              lastSyncTime: new Date().toISOString(),
              syncStatus: 'completed'
            });
            
            // 确保内存中的wordDictionary缓存也被更新
            this.wordDictionary = this.getAllWords();
            console.log('同步完成后更新wordDictionary缓存', Object.keys(this.wordDictionary).length);
            console.log('wordDictionary:',this.wordDictionary)
            // 调用传入的onComplete回调
            if (options.onComplete) {
              options.onComplete(results);
            }
            
            resolve({
              success: true,
              message: `成功同步${results.length}个单词的详细信息`
            });
          },
          onError: (error) => {
            // 更新词书的同步状态为失败
            this.updateBook(bookId, {
              lastSyncTime: new Date().toISOString(),
              syncStatus: 'failed'
            });
            
            reject(error);
          }
        });
      } catch (error) {
        console.error('同步词书单词数据失败:', error);
        reject(error);
      }
    })
  }

  /**
   * 初始化方法，用于设置wordLearningDataManager和迁移旧数据
   * @param {Object} wordLearningDataManager - WordLearningDataManager实例
   */
  initialize(wordLearningDataManager = null) {
    try {
      // 优先使用传入的wordLearningDataManager
      if (wordLearningDataManager) {
        this.wordLearningDataManager = wordLearningDataManager;
      }
      
      // 执行数据迁移
      if (this.wordLearningDataManager && typeof this.wordLearningDataManager.migrateFromOldData === 'function') {
        // 获取所有单词数据并传递给迁移方法
        const allWords = this.getAllWords();
        const result = this.wordLearningDataManager.migrateFromOldData(allWords);
        if (result.success && result.migrated) {
          console.log('学习数据迁移成功');
          // 如果有数据被迁移，保存更新后的单词数据
          this._saveWords(allWords);
        }
      }
    } catch (error) {
      console.error('数据初始化失败:', error);
    }
  }
  
  /**
   * 获取单词数据管理器的单例实例
   * @returns {WordDataManager} 单词数据管理器实例
   */
  static getInstance() {
    if (!instance) {
      instance = new WordDataManager();
    }
    return instance;
  }
} 

// 导出类和单例实例
module.exports = {
  WordDataManager,
  getInstance: WordDataManager.getInstance,
  getWordDataManager: WordDataManager.getInstance
};

// 同时设置默认导出为单例实例
module.exports.default = WordDataManager.getInstance();

// 保持向后兼容性，仍提供instance属性
Object.defineProperty(module.exports, 'instance', {
  get: function() {
    return WordDataManager.getInstance();
  },
  enumerable: true,
  configurable: true
});